Ext.define('DCApp.controller.Global', {
    extend: 'Ext.app.Controller',
    requires: [
        'DCApp.view.*',
        'Ext.window.*'
    ],
    loadingText: 'Loading...',
    stores: ['Thumbnails','BFS'],
    config: {
        control: {
        	'#app-header menuitem[text=关于]':{
        		click:'onAbout'
        	},
        	'#app-header menuitem[text=注销]':{
        		click:'onLogoutClick'
        	},
        	'#app-header menuitem[text=Print Label]':{
        		click:'onPrintLabel'
        	},
            'navigation-tree': {
                selectionchange: 'onTreeNavSelectionChange'
            },
            'navigation-breadcrumb breadcrumb': {
                selectionchange: 'onBreadcrumbNavSelectionChange'
            },
            'thumbnails': {
                itemclick: 'onThumbnailClick',
                itemdblclick: 'onThumbnailClick'
            },
            'tool[regionTool]': {
                click: 'onSetRegion'
            },
            'Userlist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Userdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'Tasklist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Taglist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Tagdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'Articlelist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'ETasklist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'ETaskdetail':{
            	objnext:'objNext',
            	objprev:'objPrev',
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Attachdetail':{
            	objnext:'objNext',
            	objprev:'objPrev',
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Attachlist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Articledetail':{
            	objnext:'objNext',
            	objprev:'objPrev',
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'LOperlist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'LOperdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'Taskdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'imgpanel':{
            	editobj:'onEditObj'
            },
            'attachpanel':{
            	editobj:'onEditObj'
            }
        },
        refs: {
            viewport: 'viewport',
            navigationTree: 'navigation-tree',
            navigationBreadcrumb: 'navigation-breadcrumb',
            contentPanel: 'contentPanel',
            descriptionPanel: 'descriptionPanel',
            thumbnails: {
                selector: 'thumbnails',
                xtype: 'thumbnails',
                autoCreate: true
            }
        },
		routes: {
			':node': {
				action:'onRouteChange',
				before:'beforeHandleRoute'
			},
			//c4w
			'(:en)detail/:id':{
				action     : 'showDetail'
			}
		},
	},
    onPrintLabel:function(item,e,opts){
    	var st = Ext.StoreMgr.get('navigation');
    	var func_print=function(obj){
    		var items = obj.items;
    		if(items){    			
    			for(var i=0; i<items.length; i++){
    				func_print(items[i]);
    			}
    		}else{
    			if(obj.fieldLabel){
    				console.log(obj.fieldLabel+':'+obj.bind);
    			}    			
    		}
    	};
    	st.each(function(rec){
    		var nl = rec.id;
    		if(nl.indexOf('list')==-1)
    			return;
	     	var nd = nl.replace('list','detail');
	     	var className = Ext.ClassManager.getNameByAlias('widget.'+nd);
	        var ViewClass = Ext.ClassManager.get(className);
 			if(!ViewClass)
 				return;
 			console.group('-----------'+rec.get('text')
 				+'['+Ext.String.capitalize(nl.substring(0,nl.length-4))+']'
 				+'-------------');
    		func_print(ViewClass.prototype);
    		console.groupEnd();
    	},this);
    },
    onLogoutClick:function(item,e,opts){
    	var me=this;
    	Ext.MessageBox.confirm('确认注销', '真的要舍我而去吗?',
			function(btn, text) {
				if (btn != 'yes')
					return false;
			me.loginManager.logout();
    	});
    },
    onAbout:function(item,e){
    	Ext.MessageBox.show({
			title:'关于', 
			icon: Ext.MessageBox.INFO,
			animEl:item,
			msg:'<p align=\'center\'>'+DCApp.Cfg.APP_NAME+DCApp.Cfg.ABOUT+'</p>',
			buttons: Ext.MessageBox.OK,
			width:220
		});
    },
    setOrigUri:function(uri){
    	this.ouri = uri;
    },
    getOrigUri:function(){
    	return this.ouri;
    },
    showDetail:function(p1,p2,p3){
		//console.log('showDetail:'+p1+":"+p3);
		var me=this;
        var pinf = me.open_info;
		if(pinf){   
            //TODO 向前/向后/返回／保存        
			return me.viewObj(pinf.rec,p3,pinf.nd,pinf);
		}
		var pdetail = p1+'detail';
		if(!DCApp.Cfg.usrInfo){
			me.setOrigUri(pdetail+'/'+p3);
			return me.showLogin();
		}
		var className = 'DCApp.model.'+Ext.String.capitalize(p1);
    	var modelClass = Ext.ClassManager.get(className);
    	//不符合detail命名规则的走VIP通道
    	if(!modelClass){
    		modelClass=Ext.ClassManager.get('DCApp.model.'+detailCMap[p1]);
    	}
    	if(!modelClass)
    		return false;
    	var pm={};
    	pm[modelClass.idProperty||'id']=parseInt(p3);
    	var obj = modelClass.create(pm);
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,p3,pdetail);
    	    }
    	});
    	
    },
    
    onEditObj:function(vw,rec){
    	
    	var vm = vw.getViewModel();
     	var nd = vm.type.replace('list','detail');
     	var ds = vw.getStore();
        var className = Ext.ClassManager.getNameByAlias('widget.'+nd);
        var ViewClass = Ext.ClassManager.get(className);

    	var cmp = new ViewClass({viewModel: {
            data: {
            	theObj: rec,
            	showprev:false,
            	shownext:false,
            	showsave:true && !DCApp.Cfg.bView,
            	showpayCalculate:true && !DCApp.Cfg.bView,
            	showreturn:false
            }
        }});    
    	
     	var dlg = Ext.create('Ext.window.Window', {
     		scrollable :true,
     		maximized:true,
     		//layout: 'fit',
     		items:[cmp],
     		listeners:{
     			close:function(win,eopts){
     				vw.detail_open=false;
     			}
     		}
    	});
     	dlg.show();
     	vw.detail_open=true;
    },
    onOpenObj:function(vw,rec,action){
    	//var vm = vw.getViewModel();
    	//var nd = this.getView().getXType().replace('detail','list');
    	var nl = vw.getXType();
     	var nd = nl.replace('list','detail');
     	var ds = vw.getStore();
     	var pos = ds.indexOf(rec);
     	if(pos==-1){
     		rec.set('id',-1);
     	}
     	
     	this.open_info={
     		list:vw,
     		rec:rec,
     		nd:nd,nl:nl,
     		rec_prev : ds.getAt(pos-1),
     		rec_next : ds.getAt(pos+1),
     		scroll_y : vw.getView().getScrollY(),
     		action:action
     	};
    	this.redirectTo(nd + '/'+ rec.id);
    },
    objNext:function(){    	
    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_next;
     	var pos = ds.indexOf(rec);
     	inf.rec_prev= inf.rec;
     	inf.rec=inf.rec_next;
     	inf.rec_next = ds.getAt(pos+1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },
    objPrev:function(){
    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_prev;
     	var pos = ds.indexOf(rec);
     	inf.rec_next= inf.rec;
     	inf.rec=inf.rec_prev;
     	inf.rec_prev = ds.getAt(pos-1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },
      
    
viewObj:function(rec,id,detail_type,pinf){
		
	var inf = pinf ||{};
	var data = {
		theObj: rec,
		showprev:Boolean(inf.rec_prev),
		shownext:Boolean(inf.rec_next),
		showsave:true,
		showreturn:inf.true
	};
	var vm = {
		data: data
	};

	var me = this,
	mainCard = this.getContentPanel(),
	mainLayout = mainCard.getLayout(),
	view = detail_type,
	lastView = me.lastView,
	existingItem = mainCard.child('component[routeId=' + detail_type + ']'),
	newView;

    // Kill any previously routed window
    if (lastView && lastView.isWindow) {
        lastView.destroy();
    }

    lastView = mainLayout.getActiveItem();

    if (!existingItem) {
        newView = Ext.create({
            xtype: detail_type,
            routeId: detail_type,  // for existingItem search later
            hideMode: 'offsets',
            viewModel:vm
        });
    }else{
        existingItem.getViewModel().setData(data);      
    } 

    if (!newView || !newView.isWindow) {
        // !newView means we have an existing view, but if the newView isWindow
        // we don't add it to the card layout.
        if (existingItem) {
            // We don't have a newView, so activate the existing view.
            if (existingItem !== lastView) {
                mainLayout.setActiveItem(existingItem);
            }
            newView = existingItem;
        }
        else {
            // newView is set (did not exist already), so add it and make it the
            // activeItem.
            Ext.suspendLayouts();
            mainLayout.setActiveItem(mainCard.add(newView));
            Ext.resumeLayouts(true);
        }
    }
    me.lastView = newView;		
},
openObj:function(){
    	var contentPanel = this.getContentPanel();
    	var myMask = new Ext.LoadMask({
    	    msg    : '正在打开',
    	    target : contentPanel
    	});

    	myMask.show();
    	this.grid_hides = contentPanel.removeAll(false);
    	var list = this.open_info.list;
    	var cmp = list.detail;
    	if(!cmp){
	        var className = Ext.ClassManager.getNameByAlias('widget.'+this.open_info.nd);
	        var ViewClass = Ext.ClassManager.get(className);
	
	    	cmp = new ViewClass({viewModel: {
	            data: {
	            	theObj: this.open_info.rec,
	            	showprev:Boolean(this.open_info.rec_prev),
	            	shownext:Boolean(this.open_info.rec_next),
	            	showsave:true&& !DCApp.Cfg.bView,
	            	showpayCalculate:true&& !DCApp.Cfg.bView,
	            	showreturn:true
	            }
	        }});    
	       // list.detail=cmp;
    	}else{
	        cmp.getViewModel().bind({data: {
	            	theObj: this.open_info.rec
	            }},function(d){
	        	//console.log(d);
	        });
	        cmp.updateLayout();
    	}
        //建立list与对应detail的双向指向，以支持detail的返回 下一条，detail的直接复用。
        cmp.masker = myMask;
    	contentPanel.add(cmp);
    },

    setCurrentView: function(hashTag) {
        hashTag = (hashTag || '').toLowerCase();

        var me = this,
            mainCard = me.getContentPanel(),
			mainLayout = mainCard.getLayout(),
			//可能没有显示tree
            navigationList = me.getNavigationTree(),
            store = store = Ext.StoreMgr.get('navigation'),
            node = store.findNode('routeId', hashTag) ||
                   store.findNode('viewType', hashTag),
            view = (node && node.get('viewType')) || 'page404',
            lastView = me.lastView,
            existingItem = mainCard.child('component[routeId=' + hashTag + ']'),
            newView;

        // Kill any previously routed window
        if (lastView && lastView.isWindow) {
            lastView.destroy();
        }

        lastView = mainLayout.getActiveItem();

        if (!existingItem) {
            newView = Ext.create({
                xtype: view,
                routeId: hashTag,  // for existingItem search later
                hideMode: 'offsets'
            });
        }

        if (!newView || !newView.isWindow) {
            // !newView means we have an existing view, but if the newView isWindow
            // we don't add it to the card layout.
            if (existingItem) {
                // We don't have a newView, so activate the existing view.
                if (existingItem !== lastView) {
                    mainLayout.setActiveItem(existingItem);
                }
                newView = existingItem;
            }
            else {
                // newView is set (did not exist already), so add it and make it the
                // activeItem.
                Ext.suspendLayouts();
                mainLayout.setActiveItem(mainCard.add(newView));
                Ext.resumeLayouts(true);
            }
        }
		if(navigationList)
        	navigationList.setSelection(node);

        me.lastView = newView;
    },

    beforeHandleRoute: function(id, action) {
        var me = this;
    	if(!me.user){
    		me.setOrigUri(id);
    		me.showLogin();
    		return false;
		}
		var store = Ext.StoreMgr.get('navigation');
        var node = store.findNode('viewType', id) || store.getNodeById(id);;

        if (node) {
            //resume action
            action.resume();
        } else {
            Ext.Msg.alert(
                'Route Failure',
                'The view for ' + id + ' could not be found. You will be taken to the application\'s start',
                function() {
                    me.redirectTo(me.getApplication().getDefaultToken());
                }
            );

            //stop action
            action.stop();
        }
    },
    onRouteChange:function(id){
		var store = Ext.StoreMgr.get('navigation');
		var node = store.findNode('viewType', id) || store.getNodeById(id);
		var me = this;
		me.updateTitle(node);
		if(node.isLeaf()){
			me.setCurrentView(id);
		}else{
			
			var navigationTree = me.getNavigationTree(),
				navigationBreadcrumb = me.getNavigationBreadcrumb(),
				store = Ext.StoreMgr.get('navigation'),
				contentPanel = me.getContentPanel(),
				thumbnails = me.getThumbnails(),
				hasTree = navigationTree && navigationTree.isVisible();
				if (hasTree) {
					if (id !== 'all') {
						// If the node is the root (rootVisible is false), then
						// Focus the first node in the tree.
						navigationTree.ensureVisible(node.isRoot() ? store.getAt(0) : node, {
							select: true,
							focus: true
						});
					}
				}
				// Ensure that non-leaf nodes are still highlighted and focused.
				else {
					navigationBreadcrumb.setSelection(node);
				}
				thumbnailsStore = me.getThumbnailsStore();
				thumbnailsStore.removeAll();
				thumbnailsStore.add(node.childNodes);

				//contentPanel.add(thumbnails);
				contentPanel.setActiveItem(thumbnails);
				Ext.resumeLayouts(true);						
		}        
    },

    
    updateTitle: function(node) {
        var text = node.get('text'),
            title = node.isLeaf() ? (node.parentNode.get('text') + ' - ' + text) : text;
        
        this.getContentPanel().setTitle(title);
        document.title = document.title.split(' - ')[0] + ' - ' + text;
    },


    exampleRe: /^\s*\/\/\s*(\<\/?example\>)\s*$/,
    themeInfoRe: /this\.themeInfo\.(\w+)/g,

    renderCodeMarkup: function(loader, response) {
        var code = this.processText(response.responseText, loader.themeInfo);
        // Passed in from the block above, we keep the proto cloned copy.
        loader.resource.html = code;
        loader.getTarget().setHtml(code);
        //prettyPrint();
        return true;
    },

    processText: function (text, themeInfo) {
        var lines = text.split('\n'),
            removing = false,
            keepLines = [],
            len = lines.length,
            exampleRe = this.exampleRe,
            themeInfoRe = this.themeInfoRe,
            encodeTheme = function (text, match) {
                return Ext.encode(themeInfo[match]);
            },
            i, line, code;

        for (i = 0; i < len; ++i) {
            line = lines[i];
            if (removing) {
                if (exampleRe.test(line)) {
                    removing = false;
                }
            } else if (exampleRe.test(line)) {
                removing = true;
            } else {
                // Replace "this.themeInfo.foo" with the value of "foo" properly encoded
                // for JavaScript (otherwise strings would not be quoted).
                line = line.replace(themeInfoRe, encodeTheme);
                keepLines.push(line);
            }
        }

        code = Ext.htmlEncode(keepLines.join('\n'));
        return '<pre class="prettyprint">' + code + '</pre>';
    },

    onSetRegion: function (tool) {
        var panel = tool.toolOwner;

        var regionMenu = panel.regionMenu || (panel.regionMenu =
            Ext.widget({
                xtype: 'menu',
                items: [{
                    text: 'North',
                    checked: panel.region === 'north',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('north');
                    }
                },{
                    text: 'South',
                    checked: panel.region === 'south',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('south');
                    }
                },{
                    text: 'East',
                    checked: panel.region === 'east',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('east');
                    }
                },{
                    text: 'West',
                    checked: panel.region === 'west',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('west');
                    }
                }]
            }));

        regionMenu.showBy(tool.el);
    },

    onTreeNavSelectionChange: function(selModel, records) {
    	if(this.open_info){
    		delete this.open_info;
    	}
        var record = records[0];

        if (record) {
            this.redirectTo(record.get('viewType')||record.get('id'));
        }
    },

    onBreadcrumbNavSelectionChange: function(breadcrumb, node) {
        if (node) {
            this.redirectTo(node.getId());
        }
    },

    onThumbnailClick: function(view, node, item, index, e) {
        var navigationTree = this.getNavigationTree();

        // If not using breadcrumb nav, drive the app through the tree's normal selection listener
        // This ensures that the tree is scrolled correctly with the correct node highlighted.
        if (navigationTree && navigationTree.isVisible()) {
            navigationTree.ensureVisible(node, {
                select: true,
                focus: true
            });
        } else {
        	var idd = node.data['idd'];
        	if(idd)
        		idd+='/-1';
            this.redirectTo(idd||node.getId());
        }
    },
    onLogin: function (view, user,  loginManager) {
		if (this.login) {
			this.login.destroy();
			delete this.login;
		}
		this.loginManager = loginManager;
		loginManager.url_home = window.location.href;
        //this.organization = organization;
        this.user = user;       
        this.showUI(view);
    },
    
    showUI: function(view) {
        Ext.create('DCApp.store.Navigation', {
            storeId: 'navigation'
        });
   	var me = this;
        me.viewport = new DCApp.view.main.Main({
            session: this.session,
            viewModel: {
                data: {
                    currentOrg: this.organization,
                    currentUser: this.user
                }
            }
        });
        var url = me.getOrigUri()||'all';
        //不是通过login窗口登录的之后会有route来到，不需要重复调用redirectTo
        if(view)
        	me.redirectTo(url,true);
    },
    showLogin:function(){
    	if(this.login)
			return;
		this.login = new DCApp.view.login.Login({
			session: this.session,
			autoShow: true,
			listeners: {
				scope: this,
				login: 'onLogin'
			}
        });
    },
    onLaunch: function () {
		var me = this;
		var token = Ext.util.Cookies.get("accessToken");
		if ((token != null) && (token != "")) {
			if (!me.loginManager) {
				me.loginManager = new DCApp.LoginManager({
					session: null,
					model: 'User'
				});
			}
			var data={accessToken:token};
			me.loginManager.login({
				data: data,
				scope: me,
				success: function(user){
					var hash = window.location.hash;
					if((hash != null) && (hash != "") && (hash.length>0)) {
						hash = hash.substring(1);
						me.setOrigUri(hash);
					}
					this.onLogin(null, user, me.loginManager);
				},
				failure: function(){
					me.showLogin();
				}
			});
		} else {
			me.showLogin();
		}
    }

});
